import java.io.*;

/**
 * 使用缓冲流对文件进行读写
 * Created by ruwenbo on 2018/6/18.
 */
public class TestBufferWriterAndReader {

    public static void main(String[] args) throws IOException {

        writeToFile();
        readFromFile();
    }

    /**
     * 使用缓冲流从文件中读取内容
     */
    private static void readFromFile() throws IOException {

        File file = new File("E:\\", "a.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        System.out.println(sb.toString());
        System.out.println("从文件中读取内容success");
    }

    /**
     * 使用缓冲流往文件中写入内容
     */
    private static void writeToFile() throws IOException {

        File file = new File("E:\\", "a.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        String content = "使用缓冲流往文件中写入内容";
        writer.write(content);
        content = "使用newLine换行往文件中再次写入内容";
        writer.newLine();
        writer.write(content);
        writer.flush();
        writer.close();
        System.out.println("使用缓冲流往文件中写入内容success");
    }
}
